package com.lenovo.smarttraffic.ui.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.ParkExtra;
import com.lenovo.smarttraffic.bean.ParkInfoBean;
import com.lenovo.smarttraffic.ui.adapter.MyMapRecyclerViewAdapter;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Caleb.F
 * on 2019-11-17
 * at 22:45
 */
public class MapActivity extends BaseActivity implements View.OnClickListener {
    private MapView mMapView;
    private AMap amap;
    private ImageView mImageView1;
    private ImageView mImageView2;
    private ImageView mImageView3;
    private ImageView mImageView4;
    private RecyclerView mRecyclerView;
    private List<ParkInfoBean.ROWSDETAILBean> mlist;
    private static final String PARK_DETAIL_EXTRA="com.lenovo.smarttraffic.ui.activity.MapActivity.parkextra";
    private static final String TAG = "MapActivity";
    private static final Integer[] PARKINFO = new Integer[]{R.mipmap.marker_one,
            R.mipmap.marker_second, R.mipmap.marker_thrid, R.mipmap.marker_forth, R.mipmap.marker_fifth, R.mipmap.marker_sixth};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        mMapView.onCreate(savedInstanceState);
        if (amap == null) {
            amap = mMapView.getMap();
        }
        amap.setMapType(AMap.MAP_TYPE_NORMAL);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_map;
    }


    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

    private void initView() {
        mMapView = findViewById(R.id.map_view);
        mImageView1 = findViewById(R.id.imageView_1);
        mImageView2 = findViewById(R.id.imageView_2);
        mImageView3 = findViewById(R.id.imageView_3);
        mImageView4 = findViewById(R.id.imageView_4);
        mRecyclerView = findViewById(R.id.map_recyclerview);

        mImageView1.setOnClickListener(this);
        mImageView2.setOnClickListener(this);
        mImageView3.setOnClickListener(this);
        mImageView4.setOnClickListener(this);
        initToolBar("用户停车");
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_1:
                initMarker();
                break;
            case R.id.imageView_2:
                break;
            case R.id.imageView_3:
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
                break;
            case R.id.imageView_4:
                Intent intent = new Intent(MapActivity.this, MapLineActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void initRecyclerView() {
        mRecyclerView.setVisibility(View.VISIBLE);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        MyMapRecyclerViewAdapter myMapRecyclerViewAdapter = new MyMapRecyclerViewAdapter(this, mlist);
        mRecyclerView.setAdapter(myMapRecyclerViewAdapter);
        myMapRecyclerViewAdapter.setOnIvClickListener((pos)->{
            Intent intent = new Intent(MapActivity.this, ParkDetailActivity.class);
            intent.putExtra(PARK_DETAIL_EXTRA,new ParkExtra(mlist.get(pos).getName(),
                    mlist.get(pos).getAddress(),Math.round(mlist.get(pos).getDistance()),
                    mlist.get(pos).getAverageRate(),mlist.get(pos).getAllSpace(),
                    mlist.get(pos).getEmptySpace(),getMaxiumRate(mlist.get(pos).getRemarks()),mlist.get(pos).getCoordinate()));
            startActivity(intent);

        });
        amap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (mRecyclerView.getVisibility() == View.VISIBLE) {
                    mRecyclerView.setVisibility(View.GONE);
                }

            }
        });
        amap.setOnMarkerClickListener(marker -> {
            if (marker.getTitle().equals("停车场")) {
                if (mRecyclerView.getVisibility() == View.GONE) {
                    mRecyclerView.setVisibility(View.VISIBLE);
                }
                return true;
            } else {
                return false;
            }
        });
    }

    private Integer getMaxiumRate(String str){
        Pattern pattern = Pattern.compile("[^0-9]");
        String trim = pattern.matcher(str).replaceAll("").trim();
        return Integer.parseInt(trim);
    }
    private void drawMark() {
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (int i = 0; i < mlist.size(); i++) {
            //记录停车场Id
            mlist.get(i).setParkerId(i + 1);
            LatLng latLng = new LatLng(Double.parseDouble(mlist.get(i).getCoordinate().split(",")[1]), Double.parseDouble(mlist.get(i).getCoordinate().split(",")[0]));
            amap.addMarker(new MarkerOptions().position(latLng).title("停车场").icon(BitmapDescriptorFactory.
                    fromBitmap(BitmapFactory.decodeResource(getResources(), PARKINFO[i]))));
            builder.include(latLng);
        }
        LatLngBounds build = builder.build();

        amap.moveCamera(CameraUpdateFactory.newLatLngBounds(build,150));
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    getParkInfo();
                    break;
                case 2:
                    getAverageRate();
                    break;
                case 3:
                    drawMark();
                    initRecyclerView();
                    break;
            }
            return false;
        }
    });

    private void getAverageRate() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("RateType", "Count");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        VolleyUtil.post("GetParkRate.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                if (jsonObject.optString("RESULT").equals("S")) {
                    for (ParkInfoBean.ROWSDETAILBean item :
                            mlist) {
                        item.setAverageRate(jsonObject.optInt("Money"));
                    }
                    Message message = new Message();
                    message.what = 3;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }

        private void getParkInfo() {
            VolleyUtil.post("GetCarParkInfo.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                ParkInfoBean parkInfoBean = new Gson().fromJson(jsonObject.toString(),ParkInfoBean.class);
                if (parkInfoBean.getRESULT().equals("S")) {
                    mlist = parkInfoBean.getROWS_DETAIL();
                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
        }

    private void initMarker() {
        LatLng latLng = new LatLng(39.941853, 116.385307);
        amap.addMarker(new MarkerOptions().position(latLng).title("什刹海").icon(BitmapDescriptorFactory
                .fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.marker_self))));
        //转换视角
        amap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,13));


    }

    public static ParkExtra getIntentData(Intent data){
        return (ParkExtra) data.getSerializableExtra(PARK_DETAIL_EXTRA);
    }
}
